package com.dg.cuckoo.admin.service.impl;

import com.dg.cuckoo.admin.dto.basicInformation.label.OneLabelDto;
import com.dg.cuckoo.admin.repository.OneLabelRepository;
import com.dg.cuckoo.admin.service.OneLabelService;
import com.dg.cuckoo.common.utils.PageModel;
import com.dg.cuckoo.core.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OneLabelServiceimpl implements OneLabelService {

    @Autowired
    private OneLabelRepository repository;

    @Override
    public void save(OneLabelDto dto) {
        saveCheck(dto);
        if(dto.getHeadLabel()==null){
            dto.setHeadLabel(0);
        }

        dto.setStatus(1);
        repository.save(dto);
    }

    @Override
    public void delect(String id) {
        if(id==null){
            throw new ServiceException("请选择标签");
        }
        repository.deleteById(id);
    }

    @Override
    public void start(String id) {
        if(id==null){
            throw new ServiceException("请选择标签");
        }
        OneLabelDto dto = repository.findById(id).get();
        dto.setStatus(1);
        repository.save(dto);
    }

    @Override
    public void disable(String id) {
        if(id==null){
            throw new ServiceException("请选择标签");
        }
        OneLabelDto dto = repository.findById(id).get();
        dto.setStatus(0);
        repository.save(dto);
    }

    @Override
    public OneLabelDto select(String id) {
        if(id==null){
            throw new ServiceException("请选择标签");
        }
        return repository.findById(id).get();
    }

    @Override
    public List<OneLabelDto> selectAll() {
        return repository.findAll();
    }

    @Override
    public PageModel page(Integer page, Integer pageSize) {
        Integer one = page;
        page = (page - 1) * pageSize;
        int size = repository.findAll().size();
        System.err.println("page:"+page);
        System.err.println("pageSize:"+pageSize);
        List<OneLabelDto> list = repository.page(page, pageSize);
        return new PageModel(one,pageSize,size,list);
    }

    @Override
    public void update(String id, OneLabelDto dto) {
        if(id==null){
            throw new ServiceException("请选择行");
        }
        dto.setId(id);
        repository.save(dto);
    }

    public void saveCheck(OneLabelDto dto){
        if(dto.getSerialNumber()==null){
            throw new ServiceException("序号不能为空");
        }
        if(dto.getLabelName()==null){
            throw new ServiceException("标签名称不能为空");
        }
        OneLabelDto name = repository.findByLabelName(dto.getLabelName());
        if(dto.getLabelName().equals(name)){
            throw new ServiceException("标签名称重复，请重新输入");
        }

    }

}
